import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 10000 // request timeout
})

// request interceptor
request.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  response => {
    const res = response.data
    if (res.message != null && res.message.indexOf('登录') != -1) {
      store.dispatch('user/resetToken').then(() => {
        location.reload()
      })
    }
    if (res.message != null && res.message.indexOf("权限") != -1) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      })
      return
    }
    return Promise.resolve(response)
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// get请求
export function get(parameter, url) {
  const headers = {}
  const token = store.getters.token
  if (token) headers.token = token

  return request({
    url: url,
    method: 'get',
    headers: headers,
    params: parameter
  })
}
// 上传图片
export function post2(parameter, url) {
  let headers = {};
  const token = store.getters.token
  if (token) headers.token = token;
  return request({
    url: url,
    method: 'post',
    headers: headers,
    data: parameter
  });
}

export default request
